package com.zy.pro.user.web;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.log4j.chainsaw.Main;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zy.core.model.PageView;
import com.zy.core.web.BaseController;
import com.zy.pro.shop.model.Cases;
import com.zy.pro.shop.service.CasesService;
import com.zy.pro.shop.web.form.CasesSearchForm;
import com.zy.pro.system.SystemCnt;
import com.zy.pro.system.web.form.GlobalForm;
import com.zy.pro.system.web.form.MenuForm;
import com.zy.pro.user.model.User;
import com.zy.pro.user.service.UserService;
import com.zy.utils.MailInfo;
import com.zy.utils.MethodUtil;
import com.zy.utils.SessionUtils;
import com.zy.utils.SimpleMailSender;
import com.zy.utils.UploadHelper;
/**
 * 系统管理员管理控制器
 *
 */
@Controller
@RequestMapping("/control/user/userController")
public class UserController extends BaseController {

	private static final Logger logger = Logger.getLogger(UserController.class);
	
	/**
	 * 系统管理员管理服务类
	 */
	@Resource(name = "userServiceImpl")
	private UserService userService;
	
	/**
	 * 案例管理服务类
	 */
	@Resource(name = "casesServiceImpl")
	private CasesService casesService;
	
	
	/**
	 * 业主注册
	 * @param user
	 * @param map
	 * @return
	 */
	@RequestMapping("/userRegister")
	public String userRegister(User user, ModelMap map, HttpServletRequest request) {
		try {
			//密码加密
			user.setPassword(MethodUtil.MD5(user.getPassword()));
			user.setUserCreateTime(new Date());//创建时间
//			user.setUserStatus(1);//用户状态1:正常,2:冻结,3:删除,4:待激活
			user.setUserStatus(4);//用户状态1:正常,2:冻结,3:删除,4:待激活
			//注册用户设置用户状态为4:待激活,发送邮件给用户,通知用户激活帐号.
			String msg = userService.saveUser(user,request);
			if("eamil success".equals(msg)){
				map.addAttribute("registerFalg", "success");
			}else{
				map.addAttribute("registerFalg", msg);
			}
//			userService.save(user);
			//map.addAttribute("registerFalg", "success");
			return "control/jsp/login/userLogin";
		} catch(Exception e){
			logger.error(e);
			return "error";
		}
	}

	/**
	 * 注册成功后激活帐号
	 * @param user
	 * @param map
	 * @return
	 */
	@RequestMapping("/activateAccount")
	public String activateAccount(User user, ModelMap map, HttpServletRequest request) {
		try {
			String message = "";
			//根据用户主键查找用户
			User userInfo = userService.find(user.getUserId());
			if(userInfo != null && userInfo.getUserStatus() == 4){
				user.setUserStatus(1);//用户状态1:正常,2:冻结,3:删除,4:待激活
				userService.updateBySelective(user);
				//用户帐号已经成功激活,欢迎登录使用
				message = "The user account has been successfully activated, welcome to log in to use";
			}else{
				if(userInfo == null){
//					message = "该用户不存在";
					message = "The user does not exist";
				}else if(userInfo.getUserStatus() == 1){
//					message = "用户可以正常使用,无需再激活";
					message = "The user can use normally, no need to activate";
				}else if(userInfo.getUserStatus() == 2){
//					message = "用户已经被冻结,请联系管理员";
					message = "The user has been frozen, please contact your administrator";
				}else if(userInfo.getUserStatus() == 3){
//					message = "用户已经被删除";
					message = "The user has been deleted";
				}
			}
			map.addAttribute("accountFalg", message);
			
			return "control/jsp/login/userLogin";
		} catch(Exception e){
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 * 用户找回密码
	 * @param user
	 * @param response
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping("/findPassword")
	public String findPassword(User user, ModelMap map, HttpServletResponse response, HttpServletRequest request) throws Exception{
		
		try {
			user = userService.findUserByEamilAndUserName(user);//查找用户信息(邮箱)
			if(user != null ){
				//初始化用户密码为123456,并发送邮件告诉用户
				String msg = userService.updateRsetPasswordAndToEmail(user, request);
				//
				if("eamil success".equals(msg)){
					map.addAttribute("accountFalg", "Email has been sent, please check");
				}else{
					map.addAttribute("accountFalg", msg);
				}
			}else{
				map.addAttribute("accountFalg", "The user does not exist");
			}
			return "control/jsp/login/userLogin";
		} catch(Exception e){
			logger.error(e);
			return "error";
		}
	}

	
	/**
	 * 业主登录
	 * @param user
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/login")
	public void login(User user, ModelMap map,HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		try {
			String message = "";
			if(user != null && user.getUserName() != null && !"".equals(user.getUserName().trim()) && user.getPassword() != null && !"".equals(user.getPassword().trim())){
				user.setPassword(MethodUtil.MD5(user.getPassword()));
				User userInfo = userService.findUserNameAndPassword(user);
				if(userInfo != null && userInfo.getUserStatus() == 1){
					userInfo.setUserOldIP(userInfo.getUserNewIP());
					if(userInfo.getUserNewLoginTime() != null){
						userInfo.setUseOldLoginTime(userInfo.getUserNewLoginTime());
					}
					userInfo.setUserNewIP(SystemCnt.getIpAddr(request));
					userInfo.setUserNewLoginTime(new Date());
					
					userService.updateBySelective(userInfo);
					
					//将店家信息放置到session当中
					SessionUtils.setUser(request, userInfo);
					SessionUtils.setRoleType(request, userInfo.getRoleType());
					response.getWriter().print(userInfo.getUserId().toString()+"success");
				}else{
					if(userInfo == null){
//						message = "该用户不存在或密码错误";
						message = "The user does not exist or password error";
					}else if(userInfo.getUserStatus() == 2){
//						message = "用户已经被冻结,请联系管理员";
						message = "The user has been frozen, please contact your administrator";
					}else if(userInfo.getUserStatus() == 4){
//						message = "用户未激活,请登录注册邮箱激活帐号";
						message = "Users are not activated, please log in registration email to activate account";
					}
					response.getWriter().print(message);
				}
			}else{
				if(user != null){
					if(user.getUserName() == null || "".equals(user.getUserName().trim())){
//						message = "用户名不能为空";
						message = "User name cannot be empty";
					}else{
//						message = "密码不能为空";
						message = "Password cannot be empty";
					}
				}else{
//					message = "用户名和密码不能为空";
					message = "The user name and password cannot be empty";
				}
				response.getWriter().print(message);
			}
		} catch(Exception e){
			logger.error(e);
		}
	}
	
	/**
	 * 显示用户中心
	 * @param user
	 * @param map
	 * @return
	 */
	@RequestMapping("/displayUser")
	public String displayUser(User user, ModelMap map) {
		try {
			//查询用户基本信息
			user = userService.find(user.getUserId());
			map.addAttribute("user", user);
			
			//查询最新的3个上架案例
			CasesSearchForm casesForm = new CasesSearchForm();
			casesForm.setCasesStatus(1);//案例状态(0:待上架,1:已上架,2:已下架)
			PageView<Cases> casesPageView = new PageView<Cases>(3, casesForm.getPage());
			casesForm.setFirstResult(casesPageView.getFirstResult());
			casesForm.setMaxResult(casesPageView.getMaxresult());
			casesPageView.setQueryResult(casesService.getData(casesForm));
			map.addAttribute("casesPageView", casesPageView);
			map.addAttribute("casesForm", casesForm);
			
			return "control/jsp/user/user";
		} catch(Exception e){
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 * 用户中心 - 展示 用户基本信息
	 * @param user
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping("/displayUserInfo")
	public String displayUserInfo(User user,HttpServletRequest request,ModelMap map){
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_INFO,MenuForm.SUB_TYPE_USER_INFO_INFO);
			map.addAttribute("menuForm", menuForm);
			
			//查询用户基本信息
			user = userService.find(user.getUserId());
			map.addAttribute("user", user);
			
			return "control/jsp/user/info";
		} catch(Exception e){
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 * 用户中心 - 展示 编辑用户基本信息页面
	 * @param user
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping("/displayEdit")
	public String displayEdit(User user,HttpServletRequest request,ModelMap map){
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_INFO,MenuForm.SUB_TYPE_USER_INFO_INFO);
			map.addAttribute("menuForm", menuForm);
			
			//查询用户基本信息
			user = userService.find(user.getUserId());
			map.addAttribute("user", user);
			
			return "control/jsp/user/editInfo";
		} catch(Exception e){
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 * 用户中心 - 编辑用户基本信息
	 * @param User
	 * @param map
	 * @return
	 */
	@RequestMapping("/edit")
	public String edit(User user,String oldUserHead ,ModelMap map,HttpServletRequest request) {
		try {
			if(user.getUserHead() != null && user.getUserHead().indexOf("yibu") != -1){
				//将异步上传的用户头像拷贝到正式路径下面
				String newPath = user.getUserHead().replaceAll("yibu", "userHead");
				UploadHelper.copyFile(user.getUserHead(), newPath, "yibu", request, logger);
				user.setUserHead(newPath);
				
				//删除旧Logo
				//UploadHelper.deletePic(oldUserHead, "userHead", request, logger);
			}
			
			userService.updateBySelective(user);
			return displayUserInfo(user,request,map);
		} catch (Exception e) {
			logger.error(e);
			return "error";
		}
		
	}
	
	/**
	 * 用户中心 - 展示密码重置
	 * @param user
	 * @param map
	 * @return
	 */
	@RequestMapping("/displayEditUserCode")
	public String displayEditUserCode(User user, ModelMap map) {
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_PASSWORD,MenuForm.SUB_TYPE_USER_PASSWORD_RES);
			map.addAttribute("menuForm", menuForm);
			
			user = userService.find(user.getUserId());
			map.addAttribute("user", user);
			
			return "control/jsp/user/user_code";
		} catch(Exception e){
			logger.error(e);
			return "error";
		}
	}
	
	/**
	 *	验证是否重复
	 * @param form
	 */
	@RequestMapping("/checkOldPassword")
	@ResponseBody
	public JSON checkOldPassword(GlobalForm form, HttpServletRequest request){
		JSONObject json = new JSONObject();
		json.put("status", "n");
		json.put("info", "The old password is incorrect!");
		try {
			//param代表用户输入的原密码(没加密的)
			//JSON代表用户真实的原密码(加密后的)
			if(form.getParam() != null && !"".equals(form.getParam())){
				boolean falg = MethodUtil.ecompareMD5(form.getParam(), form.getJson());
				if(falg){
					json.put("status", "y");
					json.put("info", "Through verification!");
					logger.info("The user to reset the password - verify the original password, verified by！");
				}
				logger.info("The user to reset the password - verify the original password verification fails, the input error！");
			}
		} catch (Exception e) {
			logger.error("The user to reset the password - verify the original password verification fails, the input error！",e);
		}
		return json;
	}
	
	/**
	 * 用户中心 - 密码重置
	 * @param user
	 * @param map
	 * @return
	 */
	@RequestMapping("/editUserCode")
	public String editUserCode(User user, ModelMap map) {
		try {
			//设置菜单类型
			MenuForm menuForm = new MenuForm(MenuForm.MENU_TYPE_USER,MenuForm.PAR_TYPE_USER_PASSWORD,MenuForm.SUB_TYPE_USER_PASSWORD_RES);
			map.addAttribute("menuForm", menuForm);
			
			user.setPassword(MethodUtil.MD5(user.getPassword()));
			userService.updateBySelective(user);
			map.addAttribute("user", user);
			map.addAttribute("editCodeStatus", "success");
			
			return "control/jsp/user/user_code";
		} catch(Exception e){
			logger.error(e);
			return "error";
		}
	}
	
	public static void main(String[] args) {
		String msg = SimpleMailSender.sendFileMail("zhushoulong1016@163.com", "18961057248@139.com", "zsl881016", "点击一下链接找回密码<a href='http://localhost:8080/decor/'>http://localhost:8080/decor/</a>","密码找回");
		String qqMsg = SimpleMailSender.sendFileMail("631390778@qq.com", "18961057248@139.com", "zsl881016", "点击一下链接找回密码<br><a href='http://localhost:8080/decor/'>http://localhost:8080/decor/</a>","密码找回");
		String yahooMsg = SimpleMailSender.sendFileMail("zhushoulong1016@yahoo.com", "18961057248@139.com", "zsl881016", "点击一下链接找回密码<a href='http://localhost:8080/decor/'>http://localhost:8080/decor/</a>","密码找回");
		System.out.println(msg+" : 163");
		System.out.println(qqMsg+" : QQ");
		System.out.println(yahooMsg+" : yahoo");
	}
}
